﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class PointOfSales : System.Web.UI.Page
{
    List<Bestlife.ERP.Entities.Cart_Item> shp = new List<Bestlife.ERP.Entities.Cart_Item>();
    Bestlife.ERP.BusinessRules.Shopping_Cart shoppingCheck;
    Bestlife.ERP.BusinessRules.Shopping_Cart totals;
    Boolean transact_Ok = false;
    string invoiceids = "";
    string uid = "0";
  
    decimal price;
    DataTable cartproduct = new DataTable();
    int rcpt;
    string codex;
    protected void Page_Load(object sender, EventArgs e)
    {
        error.Visible = false;
        PrintButton.Enabled = false;
        Checkout.Enabled = false;
        if (Session["cashierpos"] == null) 
        {
            Response.Redirect("Admin_Login.aspx");
        }

        if ((Session["cartview"] == null) && (Session["cart"] == null))
        {
            BindGridView();
        }
            if (Session["cartview"] != null)
        {
            cartproduct = (DataTable)Session["cartview"];
        }
        else
        {
            cartproduct = new DataTable();
            InitializeDataSource();
        }
        DATE.Text = System.DateTime.Now.Day.ToString() + "/" + System.DateTime.Now.Month.ToString() + "/" + System.DateTime.Now.Year.ToString();
    }
    protected void ASPxGridLookup1_TextChanged(object sender, EventArgs e)
    {

    }
    protected void DIS_ID_TextChanged(object sender, EventArgs e)
    {
        
    }

    #region For labels

    public void lablesvalue()
    {
    
        if (Session["cartview"] != null)
        {
            totals = (Bestlife.ERP.BusinessRules.Shopping_Cart)Session["cartview"];

            //TOTAMOUNT.Visible = false;
            //TOTPV.Visible = false;
            //TOTBV.Visible = false;

            if (totals.Items.Count > 0)
            {
         
                TOTAMOUNT.Visible = true;
                TOTPV.Visible = true;
                TOTBV.Visible = true;
                #region to recipt


                TOTAMOUNT.Text = "" + totals.total;
                TOTPV.Text = "" + totals.totalPoint_value;
                TOTBV.Text = "" + totals.totalBusiness_Value;
                TOTDIS.Text = "" + totals.Tot_discounttot;
                TOTRETAIL.Text = "" + totals.total_Rprice;
                TOTQTY.Text = "" + totals.total_quantity;


                #endregion

            }

        }
    }


    #endregion


    protected void Add_Click(object sender, EventArgs e)
    {
   
        try
        {
            List<object> items = new List<object>();
            List<object> code = new List<object>();
        //   ASPxGridView1.GetSelectedFieldValues("Pro_ID", "Code", "Pro_Price", "Pro_Name", "Business_Value", "Point_Value");

                items.Clear();
                code.Clear();

        items = ASPxGridView1.GetSelectedFieldValues("Pro_ID");
        code = ASPxGridView1.GetSelectedFieldValues("Code");

        if (items.Count == 0 && code.Count == 0)
        {        
            error.Visible = true;
            error.Text = "Please Select an Item";
        }
        else
        {
            Checkout.Enabled = true;
            error.Visible = false;
            foreach (object it in items)
            {
                Label1.Text = it.ToString();
            }
            items.Clear();

            //Code

            foreach (object cd in code)
            {
                Label7.Text = cd.ToString();
            }
            code.Clear();


            bool bb = false;

            Bestlife.ERP.Entities.ProductE Re_Product = Bestlife.ERP.DataAccess.ProductDA.GetProuctforPOS(Label1.Text, Label7.Text);
            Bestlife.ERP.DataAccess.D_Stock stock = new Bestlife.ERP.DataAccess.D_Stock();
            decimal qty = stock.ReturnStockQuantity(Re_Product.Product_ID, Re_Product.Code);



            if (qty > 0)
            {
                #region Insert To Cart

                int rowc = cartproduct.Rows.Count;
                DataView dv1 = new DataView(cartproduct);

                foreach (DataRowView drv in dv1)
                {

                    string dr = drv.Row["ID"].ToString();
                    string cd = drv.Row["Code"].ToString();
                    //Label4.Text = dr;
                    if (dr.Equals(Re_Product.Product_ID) && cd.Equals(Re_Product.Code))
                    {
                        Label1.Text = "Please use the edit button to update the quantity";
                        Label5.Text = "";
                        bb = true;
                    }

                }

                if (!bb)
                {

                    string Quntity = "1";

                    cartproduct.Rows.Add(Re_Product.Product_ID, Re_Product.Code, Re_Product.Pro_Name, Re_Product.Pro_Price, Re_Product.Ret_Price, Re_Product.Point_Value, Re_Product.Business_Value, Quntity);
                    Session["cartview"] = cartproduct;
                    GridView1.DataSource = Session["cartview"];
                    GridView1.DataBind();

                    #region Ontime Calculation

                    double tot = 0;
                    double Tpv = 0;
                    double Tbv = 0;

                    foreach (GridViewRow rws in GridView1.Rows)
                    {


                        string proid = rws.Cells[0].Text;
                        codex = rws.Cells[1].Text;
                        Bestlife.ERP.Entities.ProductE productDetails = Bestlife.ERP.DataAccess.ProductDA.GetProuctforPOS(proid, codex);

                        double pvs = double.Parse(productDetails.Point_Value.ToString());
                        double bvs = double.Parse(productDetails.Business_Value.ToString());
                        string price = rws.Cells[3].Text;

                        Label _txt = rws.FindControl("Label3") as Label;
                        string Quantity = _txt.Text;

                        if (Quantity.Equals(""))
                        {
                            Quantity = "1"; 
                        }

                        tot = tot + (double.Parse(price) * (double.Parse(Quantity)));//total Price
                        Tpv = Tpv + (pvs * (double.Parse(Quantity)));
                        Tbv = Tbv + (bvs * (double.Parse(Quantity)));

                        TOTAMOUNT.Visible = true;
                        TOTPV.Visible = true;
                        TOTBV.Visible = true;
                        TOT.Visible = true;

                        TOTAMOUNT.Text = tot.ToString();
                        TOTPV.Text = Tpv.ToString();
                        TOTBV.Text = Tbv.ToString();
                        TOT.Text = tot.ToString();

                    }

                    #endregion

                    //lablesvalue();


                }
                Label5.Text = "";
                //BindGridView();
                // }
                #endregion
            }
            else
            {
                Label5.Text = "This Item is Out of Stock";
            }
        }
        }
              catch (Exception ee)
            {
                string msg = ee.ToString();
                string[] arr = msg.Split('.');
                string message1 = arr[1].ToString();
                Response.Redirect("404.aspx?msg='" + message1 + "'");
            }
            
       
    }


   
    private void InitializeDataSource()
    {
        try
        {
           // Add four columns to the DataTable.
            cartproduct.Columns.Add("ID");
            cartproduct.Columns.Add("Code");
            cartproduct.Columns.Add("Name");
            cartproduct.Columns.Add("Price");
            cartproduct.Columns.Add("R_Price");
            cartproduct.Columns.Add("PV");
            cartproduct.Columns.Add("BV");
            cartproduct.Columns.Add("Quantity");


            // Set Produt_ID n Product_code column as the primary key.
            //DataColumn[] dcKey = new DataColumn[1];
            DataColumn[] dcKey = new DataColumn[2];
            dcKey[0] = cartproduct.Columns["ID"];
            dcKey[1] = cartproduct.Columns["Code"];
            cartproduct.PrimaryKey = dcKey;
        }
        catch (Exception ee)
        {
            string msg = ee.ToString();
            string[] arr = msg.Split('.');
            string message1 = arr[1].ToString();
            Response.Redirect("404.aspx?msg='" + message1 + "'");
        }

    }

    private void BindGridView()
    {
        try
        {
            if (Session["cartview"] != null)
            {

                // Get the DataTable from ViewState.
                DataTable cartAdd = (DataTable)Session["cartview"];

                // Co nvert the DataTable to DataView.
                DataView cartvb = new DataView(cartAdd);

                // Bind the GridView control.
                GridView1.DataSource = cartvb;
                GridView1.DataBind();
                
            }
        }
        catch (Exception ee)
        {
            string msg = ee.ToString();
            string[] arr = msg.Split('.');
            string message1 = arr[1].ToString();
            Response.Redirect("404.aspx?msg='" + message1 + "'");
        }
    }
   
    public void sending_to_cart_class()
    {
        Bestlife.ERP.BusinessRules.Shopping_Cart cartsession = new Bestlife.ERP.BusinessRules.Shopping_Cart();
        Session["cart"] = cartsession;

        Boolean sta = false;
        DataView dv1 = new DataView(cartproduct);
        try
        {
            if (Session["cart"] != null)
            {
                foreach (DataRowView drv in dv1)
                {
                    string Product_ID = drv.Row["ID"].ToString();
                    string Codev = drv.Row["Code"].ToString();
                    string Pro_Name = drv.Row["Name"].ToString();
                    string Pro_Price = drv.Row["Price"].ToString();
                    string R_price = drv.Row["R_Price"].ToString();
                    string Point_Value = drv.Row["PV"].ToString();
                    string Business_Value = drv.Row["BV"].ToString();
                    string Qun = drv.Row["Quantity"].ToString();

                    Bestlife.ERP.BusinessRules.Shopping_Cart cart = (Bestlife.ERP.BusinessRules.Shopping_Cart)Session["cart"];

                    string Pr_ID = Product_ID;
                    string Code = Codev;
                    string Pr_Name = Pro_Name;
                    decimal Pr_Price = decimal.Parse(Pro_Price);
                    decimal R_Price = decimal.Parse(R_price);
                    decimal Po_Value = decimal.Parse(Point_Value);
                    decimal Bu_value = decimal.Parse(Business_Value);
                    double Qun_Tb = double.Parse(Qun);

                    cart.insertItems(Pr_ID, Code, Pr_Name, Pr_Price, R_Price, Po_Value, Bu_value, Qun_Tb);
                    sta = true;
                    //DataList1.Controls[0].FindControl("Product_ID") = Re_Product.Product_ID.ToString();                 
                }

                if (sta)
                {

                }
            }
        }
        catch (Exception ee)
        {
            string msg = ee.ToString();
            string[] arr = msg.Split('.');
            string message1 = arr[1].ToString();
            Response.Redirect("404.aspx?msg='" + message1 + "'");
        }

    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        Checkout.Enabled = true;
        GridView1.EditIndex = e.NewEditIndex;
        BindGridView();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        try
        {
            Checkout.Enabled = true;
           

            if (Session["cartview"] != null)
            {
                string tbs = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1")).Text;

                DataTable bacEdit = (DataTable)Session["cartview"];
                // Get the PersonID of the selected row.
                string Pro_ID = GridView1.Rows[e.RowIndex].Cells[0].Text;
                string Pro_code = GridView1.Rows[e.RowIndex].Cells[1].Text;
                string codex=GridView1.Rows[e.RowIndex].Cells[6].Text;
                DataRow bacEditrw = bacEdit.Rows.Find(new Object[] { Pro_ID ,Pro_code});


                Bestlife.ERP.Entities.ProductE product_check = Bestlife.ERP.DataAccess.ProductDA.GetProuctforPOS(Pro_ID, Pro_code);
                 Bestlife.ERP.DataAccess.D_Stock stock = new Bestlife.ERP.DataAccess.D_Stock();

                 decimal DBqn = stock.ReturnStockQuantity(product_check.Product_ID,product_check.Code);
                 decimal quan = decimal.Parse(bacEditrw["Quantity"].ToString());
                 //decimal st= stock.reduceStock(product_check.Pro_Name,double.Parse(bacEditrw["Quantity"].ToString()));
                Boolean st=false;
                if (DBqn>=quan)
                {
                    st = true;
                }
                 if (st==true)
                 {
                     //string Pro_Code = GridView1.Rows[e.RowIndex].Cells[2].Text;

                     // Find the row in DateTable.


                     string tbl = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1")).Text;

                     bacEditrw["Quantity"] = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1")).Text;

                     string tb = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1")).Text;

                     // Exit edit mode.
                     GridView1.EditIndex = -1;
                     //GridView1.DataBind();
                     // Rebind the GridView control to show data after updating.
                     BindGridView();

                     #region Ontime Calculation

                     double tot = 0;
                     double Tpv = 0;
                     double Tbv = 0;

                     foreach (GridViewRow rws in GridView1.Rows)
                     {
                         string proID = rws.Cells[0].Text;
                         codex =rws.Cells[1].Text;
                         Bestlife.ERP.Entities.ProductE productDetails = Bestlife.ERP.DataAccess.ProductDA.GetProuctforPOS(proID,codex);

                         double pvs = double.Parse(productDetails.Point_Value.ToString());
                         double bvs = double.Parse(productDetails.Business_Value.ToString());
                         string price = rws.Cells[3].Text;

                         Label _txt = rws.FindControl("Label3") as Label;
                         string Quantity = _txt.Text;

                         if (Quantity.Equals(""))
                         {
                             Quantity = "1";
                         }

                         tot = tot + (double.Parse(price) * (double.Parse(Quantity)));//total Price
                         Tpv = Tpv + (pvs * (double.Parse(Quantity)));
                         Tbv = Tbv + (bvs * (double.Parse(Quantity)));

                         TOTAMOUNT.Visible = true;
                         TOTPV.Visible = true;
                         TOTBV.Visible = true;
                         TOT.Visible = true;

                         TOTAMOUNT.Text = tot.ToString();
                         TOTPV.Text = Tpv.ToString();
                         TOTBV.Text = Tbv.ToString();
                         TOT.Text = tot.ToString();

                     }

                     #endregion


                 }
                 else
                 {
                     bacEditrw["Quantity"] = "1";
                     // Exit edit mode.
                     GridView1.EditIndex = -1;
                     //GridView1.DataBind();
                     // Rebind the GridView control to show data after updating.
                     BindGridView();
                     Label5.Text = "Available Quantity is " + st;            
                 }

            }
        }
        catch (Exception ee)
        {
            string msg = ee.ToString();
            string[] arr = msg.Split('.');
            string message1 = arr[1].ToString();
            Response.Redirect("404.aspx?msg='" + message1 + "'");
        }
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            Checkout.Enabled = true;
            if (Session["cartview"] != null)
            {
                // Get the DataTable from ViewState.
                DataTable delcart = (DataTable)Session["cartview"];

                // Get the PersonID of the selected row.
                string Pro_ID = GridView1.Rows[e.RowIndex].Cells[0].Text;
                string Pro_code = GridView1.Rows[e.RowIndex].Cells[1].Text;
                //string codex = GridView1.Rows[e.RowIndex].Cells[6].Text;
                DataRow bacDeltrw = delcart.Rows.Find(new Object[] { Pro_ID, Pro_code });
               

                // Remove the row from the DataTable.
                delcart.Rows.Remove(bacDeltrw);

                // Rebind the GridView control to show data after deleting.
                BindGridView();


                #region Ontime Calculation

                double tot = 0;
                double Tpv = 0;
                double Tbv = 0;

                foreach (GridViewRow rws in GridView1.Rows)
                {


                    string proid = rws.Cells[0].Text;
                    string codex=rws.Cells[1].Text;
                    Bestlife.ERP.Entities.ProductE productDetails = Bestlife.ERP.DataAccess.ProductDA.GetProuctforPOS(proid,codex);

                    double pvs = double.Parse(productDetails.Point_Value.ToString());
                    double bvs = double.Parse(productDetails.Business_Value.ToString());
                    string price = rws.Cells[3].Text;

                    Label _txt = rws.FindControl("Label3") as Label;
                    string Quantity = _txt.Text;

                    if (Quantity.Equals(""))
                    {
                        Quantity = "1";
                    }

                    tot = tot + (double.Parse(price) * (double.Parse(Quantity)));//total Price
                    Tpv = Tpv + (pvs * (double.Parse(Quantity)));
                    Tbv = Tbv + (bvs * (double.Parse(Quantity)));

                    TOTAMOUNT.Visible = true;
                    TOTPV.Visible = true;
                    TOTBV.Visible = true;
                    TOT.Visible = true;

                    TOTAMOUNT.Text = tot.ToString();
                    TOTPV.Text = Tpv.ToString();
                    TOTBV.Text = Tbv.ToString();
                    TOT.Text = tot.ToString();

                }

                #endregion


            }
        }
        catch (Exception ee)
        {
            string msg = ee.ToString();
            string[] arr = msg.Split('.');
            string message1 = arr[1].ToString();
            Response.Redirect("404.aspx?msg='" + message1 + "'");
        }
    }
    protected void ASPxGridView1_SelectionChanged(object sender, EventArgs e)
    {
       
    }
    protected void ASPxGridView1_FocusedRowChanged(object sender, EventArgs e)
    {
        
    }

    protected void ASPxButton1_Click(object sender, EventArgs e)
    {
        string Name_of_user = Session["user"].ToString();


        string nic=Name_of_user;
        string uids = "";


        string check_Ename = Name_of_user;

        int id_length = Name_of_user.Length;

        if (id_length == 10)
        {

             uids = nic.Substring(9);
            if (uids.Equals("V")||uids.Equals("v")||uids.Equals("X")||uids.Equals("x"))
            {
                uids = "Pass";
            }
        }

        if (id_length > 2)
        {
            check_Ename = Name_of_user.Substring(0, 2);
        }
        else
        {
            check_Ename = Name_of_user;
        }


        ASPxGridView1.Visible = false;
        Add.Visible = false;
        PrintButton.Enabled = true;
        sending_to_cart_class();
        GridView1.Visible = false;
        GridView2.Visible = true;
        reBind();

        if (check_Ename.Equals("EM"))
        {
            Bestlife.ERP.DataAccess.D_Employee dempl=new Bestlife.ERP.DataAccess.D_Employee();
            Bestlife.ERP.Entities.E_Employee empEn = new Bestlife.ERP.Entities.E_Employee();
            Bestlife.ERP.Entities.E_UserPurchs eupchs = new Bestlife.ERP.Entities.E_UserPurchs();
            Bestlife.ERP.DataAccess.D_UserPurchase dupchs = new Bestlife.ERP.DataAccess.D_UserPurchase();

            Bestlife.ERP.DataAccess.D_Employee emp = new Bestlife.ERP.DataAccess.D_Employee();
            empEn = emp.Employee_return(Name_of_user);

            if (empEn.Employee_iD != null)
            {
                #region insert into Receipt Table
                Bestlife.ERP.Entities.E_Receipt recept = new Bestlife.ERP.Entities.E_Receipt();

                recept.D_id = Name_of_user;
                recept.D_name = Session["name"].ToString();
                recept.Rcpt_no = rcpt;
                recept.Toatal_PV = TOTPV.Text;
                recept.Total_BV = TOTBV.Text;
                recept.Total_Price = TOTAMOUNT.Text;
                recept.Cashier_name = Session["cashierpos"].ToString();
                recept.R_date = System.DateTime.Now;

                Bestlife.ERP.DataAccess.D_Receipt drcpt = new Bestlife.ERP.DataAccess.D_Receipt();
                drcpt.inserttoReceipt(recept);

                #endregion

                #region Insert in to Tbl_UserPurchase

                string rcptnum = rcptno();

                //Response.WriteFile("www.SampathBankIPG.php/payment-gateway.php");
                //payment gateway information mst be there
                foreach (Bestlife.ERP.Entities.Cart_Item ct in shoppingCheck.Items)
                {
                    eupchs.User_ID = Name_of_user;
                    eupchs.Pro_Name1 = ct.Name;
                    eupchs.ProID = ct.ID;
                    eupchs.Code = ct.Code;
                    eupchs.Qty = ct.Quantity;
                    eupchs.Price = decimal.Parse(ct.Price.ToString());
                    eupchs.PV = decimal.Parse(ct.PV.ToString());
                    eupchs.BV = decimal.Parse(ct.BV.ToString());
                    eupchs.User_Create = Session["cashierpos"].ToString(); ;
                    eupchs.Date_Create = System.DateTime.Now;
                    eupchs.Last_modify = System.DateTime.Now;
                    eupchs.Key_Timestamp = 1;
                    eupchs.R_ids = rcptnum;
                    bool st = dupchs.UserPurchase_Add(eupchs);



                    if (st)
                    {

                        #region ReduceStock
                        Bestlife.ERP.DataAccess.D_Stock stock = new Bestlife.ERP.DataAccess.D_Stock();
                        stock.reduceStock(ct.ID,ct.Code,ct.Quantity);
                        #endregion

                        //   checkout.Visible = false;
                        Label4.Text = "Thank you for your purchase. We appreciate your business. Your order will be processed immediatley upon payment approval from Sampath Bank. At that time, an email confirmation will be sent to the email address you provided to registration. If you made an error entering your email address to registration, your purchase confirmation and tracking information may not arrive. Should you have any questions, please contact us at info@bestlife.com or call us at +94 (0)38 492 7322/ 23/ 24 between 9am and 5pm, Monday through Saturday.";
                        //Response.Redirect("Home.aspx");

                        //conf.Text = "Welcome To BestLife";

                        //backbutton.Visible = true;
                    }
                    //}
                }
                //dupchs.UserPurchase_Add();
                #endregion

                #region Update Employee Table
                Bestlife.ERP.Entities.E_Employee employ = new Bestlife.ERP.Entities.E_Employee();
                employ.Employee_iD = Name_of_user;
                employ.Employee_name = Session["name"].ToString();
                employ.T_PV = decimal.Parse(TOTPV.Text.ToString());
                employ.T_bv = decimal.Parse(TOTBV.Text.ToString());
                employ.T_price = decimal.Parse(TOTAMOUNT.Text.ToString());

                dempl.Employee_tableUp(employ);

                #endregion

            }
            else 
            {
            
            }
        }
        else if (uids.Equals("Pass"))
        {

            Bestlife.ERP.DataAccess.D_Employee dempl = new Bestlife.ERP.DataAccess.D_Employee();
            Bestlife.ERP.Entities.E_Employee empEn = new Bestlife.ERP.Entities.E_Employee();
            Bestlife.ERP.Entities.E_UserPurchs eupchs1 = new Bestlife.ERP.Entities.E_UserPurchs();
            Bestlife.ERP.DataAccess.D_UserPurchase dupchs1 = new Bestlife.ERP.DataAccess.D_UserPurchase();

            #region insert into Receipt Table
            Bestlife.ERP.Entities.E_Receipt recept = new Bestlife.ERP.Entities.E_Receipt();

            recept.D_id = Name_of_user;
            recept.D_name = Session["name"].ToString();
            recept.Rcpt_no = rcpt;
            recept.Toatal_PV = TOTPV.Text;
            recept.Total_BV = TOTBV.Text;
            recept.Total_Price = TOTAMOUNT.Text;
            recept.Cashier_name = Session["cashierpos"].ToString();
            recept.R_date = System.DateTime.Now;

            Bestlife.ERP.DataAccess.D_Receipt drcpt = new Bestlife.ERP.DataAccess.D_Receipt();
            drcpt.inserttoReceipt(recept);

            #endregion

            #region Insert in to Tbl_UserPurchase

            string rcptnum = rcptno();

            //Response.WriteFile("www.SampathBankIPG.php/payment-gateway.php");
            //payment gateway information mst be there
            foreach (Bestlife.ERP.Entities.Cart_Item ct in shoppingCheck.Items)
            {
                eupchs1.User_ID = Name_of_user;
                eupchs1.Pro_Name1 = ct.Name;
                eupchs1.ProID = ct.ID;
                eupchs1.Code = ct.Code;
                eupchs1.Qty = ct.Quantity;
                eupchs1.Price = decimal.Parse(ct.Price.ToString());
                eupchs1.PV = decimal.Parse(ct.PV.ToString());
                eupchs1.BV = decimal.Parse(ct.BV.ToString());
                eupchs1.User_Create = Session["cashierpos"].ToString(); ;
                eupchs1.Date_Create = System.DateTime.Now;
                eupchs1.Last_modify = System.DateTime.Now;
                eupchs1.Key_Timestamp = 1;
                eupchs1.R_ids = rcptnum;
                bool st = dupchs1.UserPurchase_Add(eupchs1);



                if (st)
                {

                    #region ReduceStock
                    Bestlife.ERP.DataAccess.D_Stock stock = new Bestlife.ERP.DataAccess.D_Stock();
                    stock.reduceStock(ct.ID,ct.Code,ct.Quantity);
                    #endregion

                    //   checkout.Visible = false;
                    Label4.Text = "Thank you for your purchase. We appreciate your business. Your order will be processed immediatley upon payment approval from Sampath Bank. At that time, an email confirmation will be sent to the email address you provided to registration. If you made an error entering your email address to registration, your purchase confirmation and tracking information may not arrive. Should you have any questions, please contact us at info@bestlife.com or call us at +94 (0)38 492 7322/ 23/ 24 between 9am and 5pm, Monday through Saturday.";
                    //Response.Redirect("Home.aspx");

                    //conf.Text = "Welcome To BestLife";

                    //backbutton.Visible = true;
                }
                //}
            }
            //dupchs.UserPurchase_Add();
            #endregion

        }
        else if (!idisok(Name_of_user))
        {
            Allprocess();
        }
        else {
            error.Visible = true;
            error.Text = "ID Error"; 
        }
    } 




    #region All process Methord

    public Boolean Allprocess()
    {


        string u_name = Session["user"].ToString();

        #region Entities And DataAccess Class

        Bestlife.ERP.DataAccess.D_bonus bnus = new Bestlife.ERP.DataAccess.D_bonus();
        Bestlife.ERP.Entities.E_Bonus ebns = new Bestlife.ERP.Entities.E_Bonus();

        Bestlife.ERP.DataAccess.users Us = new Bestlife.ERP.DataAccess.users();

        Bestlife.ERP.Entities.E_UserPurchs eupchs = new Bestlife.ERP.Entities.E_UserPurchs();
        Bestlife.ERP.DataAccess.D_UserPurchase dupchs = new Bestlife.ERP.DataAccess.D_UserPurchase();


        #endregion

        string UId = Us.GetUserId(u_name); // Change by thanuja (14/06/2012)//change by chathuranga get userId Using user Username 
        //    uid.Text = UId;
            #region check bestlife or vandana
        Boolean Otheraccount = false;

        if (u_name.Equals("vandana"))
        {
            Otheraccount = true;
        }
        else if (u_name.Equals("bestlife"))
        {
            Otheraccount = true;
        }

        #endregion

        if (Otheraccount == false)
        {
            #region comment
            //if (Us.GetUserTablest(UId))
        //{
        //    //Bestlife.ERP.DataAccess.Pricecheckup chkp = new Bestlife.ERP.DataAccess.Pricecheckup();
        //    //Bestlife.ERP.Entities.E_Bonus bnsback = bnus.Getbonus(UId);

        //    #region assign values

        //    //double pv = double.Parse(bnsback.Ppv.ToString());
        //    //double bv = double.Parse(bnsback.Bv.ToString());
        //    //double DbTprice = double.Parse(bnsback.T_sales.ToString());
        //    //double DbTpv = double.Parse(bnsback.Tpv.ToString());
        //    //double DbTbv = double.Parse(bnsback.Tbv.ToString());

        //    #endregion


        //    //double sTp = DbTprice + Math.Round(double.Parse(chkp.returnPrice(TOTAMOUNT.Text.ToString())),3);// Math.Round(double.Parse(chkp.returnPrice(c.Total_RAmount.ToString())), 2);
        //    //double sTpv = DbTpv + Math.Round(double.Parse(chkp.returnPrice(TOTPV.Text.ToString())),3);
        //    //double sTbv = DbTbv + Math.Round(double.Parse(chkp.returnPrice(TOTBV.Text.ToString())),3);
        //    //double sbv = bv + Math.Round(double.Parse(chkp.returnPrice(TOTBV.Text.ToString())), 3);
        //    //double spv = pv + Math.Round(double.Parse(chkp.returnPrice(TOTPV.Text.ToString())), 3);

        //    #region Update Bonus table
        //    //Us.UpdateBonus(UId, sTp, sTpv, sTbv, double.Parse(TOTPV.Text), double.Parse(TOTBV.Text));//send All Product Pv n Bvs only
        //    #endregion

        //    #region Send Values to calculation_Daily methord

        //    //Bestlife.ERP.DataAccess.calculation_Daily cals = new Bestlife.ERP.DataAccess.calculation_Daily();

        //    //// Pass Values to the calculation_Dailys class :
        //    //cals.calculation_Dailys(UId, double.Parse(TOTBV.Text), double.Parse(TOTPV.Text), double.Parse(TOTAMOUNT.Text));


        //    #endregion

        //}
        //else
        //{
        //    #region Insert To Bonus

        //    //Bestlife.ERP.BusinessRules.Check_montlyPV checkmp = new Bestlife.ERP.BusinessRules.Check_montlyPV();
        //    //int userst = checkmp.first_status(UId, double.Parse(TOTPV.Text));

        //    //ebns.User_id = UId;
        //    //ebns.Tpv = decimal.Parse(TOTPV.Text);
        //    //ebns.Ppv = decimal.Parse(TOTPV.Text);
        //    //ebns.Cpv = decimal.Parse("0");
        //    //ebns.CPV_month = decimal.Parse("0");
        //    //ebns.T_sales = decimal.Parse(TOTAMOUNT.Text);
        //    //ebns.T_commision = decimal.Parse("0");
        //    //ebns.T_Lship = decimal.Parse("0");
        //    //ebns.Subdealers_Id = "Not In Use";
        //    //ebns.CPV_month = decimal.Parse("0");
        //    //ebns.Bv = decimal.Parse(TOTBV.Text);
        //    //ebns.User_Status = userst.ToString();
        //    //ebns.Tbv = decimal.Parse(TOTBV.Text);
        //    //ebns.Storebv = 0;
        //    //ebns.Storepv = 0;
        //    //ebns.Lship_Status = 0;
        //    //ebns.Store_Lship = 0;
        //    //ebns.Storecomm = 0;
        //    //ebns.Usercreate = UId;
        //    //ebns.Date_create = System.DateTime.Now;


        //    //bool st = bnus.Bonus_Add(ebns);

        //    //if (st)
        //    //{
        //    //    //msg insert ok
        //    //}
        //    //else
        //    //{
        //    //    // msg server or Sql Error 
        //    //}


        //    #endregion

        //    #region Send Values to calculation_Daily methord

        //    //Bestlife.ERP.DataAccess.calculation_Daily cals = new Bestlife.ERP.DataAccess.calculation_Daily();

        //    //// Pass Values to the calculation_Dailys class :
        //    //cals.calculation_Dailys(UId, double.Parse(TOTBV.Text), double.Parse(TOTPV.Text), double.Parse(TOTAMOUNT.Text));


        //    #endregion
            //}
            #endregion

            #region insert into Receipt Table
            Bestlife.ERP.Entities.E_Receipt recept = new Bestlife.ERP.Entities.E_Receipt();

            recept.D_id = UId;
            recept.D_name = Session["name"].ToString();
            recept.Rcpt_no = rcpt;
            recept.Toatal_PV = TOTPV.Text;
            recept.Total_BV = TOTBV.Text;
            recept.Total_Price = TOTAMOUNT.Text;
            recept.Cashier_name = Session["cashierpos"].ToString();
            recept.R_date = System.DateTime.Now;

            Bestlife.ERP.DataAccess.D_Receipt drcpt = new Bestlife.ERP.DataAccess.D_Receipt();
            drcpt.inserttoReceipt(recept);


            #endregion

            #region Insert in to Tbl_UserPurchase

        string rcptnum = rcptno();

        //Response.WriteFile("www.SampathBankIPG.php/payment-gateway.php");
        //payment gateway information mst be there
        foreach (Bestlife.ERP.Entities.Cart_Item ct in shoppingCheck.Items)
        {
            eupchs.User_ID = UId;
            eupchs.Pro_Name1 = ct.Name;
            eupchs.ProID = ct.ID;
            eupchs.Code = ct.Code;
            eupchs.Qty = ct.Quantity;
            eupchs.Price = decimal.Parse(ct.Price.ToString());
            eupchs.PV = decimal.Parse(ct.PV.ToString());
            eupchs.BV = decimal.Parse(ct.BV.ToString());
            eupchs.User_Create = u_name;
            eupchs.Date_Create = System.DateTime.Now;
            eupchs.Last_modify = System.DateTime.Now;
            eupchs.Key_Timestamp = 1;
            eupchs.R_ids = rcptnum;
            bool st = dupchs.UserPurchase_Add(eupchs);



            if (st)
            {

                #region ReduceStock
                Bestlife.ERP.DataAccess.D_Stock stock = new Bestlife.ERP.DataAccess.D_Stock();
                stock.reduceStock(ct.ID,ct.Code,ct.Quantity);
                #endregion

                //   checkout.Visible = false;
                    Label4.Text = "Thank you for your purchase. We appreciate your business. Your order will be processed immediatley upon payment approval from Sampath Bank. At that time, an email confirmation will be sent to the email address you provided to registration. If you made an error entering your email address to registration, your purchase confirmation and tracking information may not arrive. Should you have any questions, please contact us at info@bestlife.com or call us at +94 (0)38 492 7322/ 23/ 24 between 9am and 5pm, Monday through Saturday.";
                    //Response.Redirect("Home.aspx");

                    //conf.Text = "Welcome To BestLife";

                    //backbutton.Visible = true;
                }
            //}
        }
        //dupchs.UserPurchase_Add();
        #endregion

        }
        else if (Otheraccount == true)
        {
            #region insert into Receipt Table if Vandana Or Bestlife

            Bestlife.ERP.Entities.E_Receipt recept = new Bestlife.ERP.Entities.E_Receipt();

            recept.D_id = UId;
            recept.D_name = Session["name"].ToString();
            recept.Rcpt_no = rcpt;
            recept.Toatal_PV = TOTPV.Text;
            recept.Total_BV = TOTBV.Text;
            recept.Total_Price = TOTAMOUNT.Text;
            recept.Cashier_name = Session["cashierpos"].ToString();
            recept.R_date = System.DateTime.Now;

            Bestlife.ERP.DataAccess.D_Receipt drcpt = new Bestlife.ERP.DataAccess.D_Receipt();
            drcpt.inserttoReceipt(recept);


            #endregion

            #region Insert in to Tbl_UserPurchase if Vandana Or Bestlife


            string rcptnum = rcptno();

            //Response.WriteFile("www.SampathBankIPG.php/payment-gateway.php");
            //payment gateway information mst be there
            foreach (Bestlife.ERP.Entities.Cart_Item ct in shoppingCheck.Items)
            {
                eupchs.User_ID = UId;
                eupchs.Pro_Name1 = ct.Name;
                eupchs.ProID = ct.ID;
                eupchs.Code = ct.Code;
                eupchs.Qty = ct.Quantity;
                eupchs.Price = decimal.Parse(ct.Price.ToString());
                eupchs.PV = decimal.Parse(ct.PV.ToString());
                eupchs.BV = decimal.Parse(ct.BV.ToString());
                eupchs.User_Create = u_name;
                eupchs.Date_Create = System.DateTime.Now;
                eupchs.Last_modify = System.DateTime.Now;
                eupchs.Key_Timestamp = 1;
                eupchs.R_ids = rcptnum;
                bool st = dupchs.UserPurchase_Add(eupchs);



                if (st)
                {

                    #region ReduceStock
                    Bestlife.ERP.DataAccess.D_Stock stock = new Bestlife.ERP.DataAccess.D_Stock();
                    stock.reduceStock(ct.ID,ct.Code,ct.Quantity);
                    #endregion

                    //   checkout.Visible = false;
                    Label4.Text = "Thank you for your purchase. We appreciate your business. Your order will be processed immediatley upon payment approval from Sampath Bank. At that time, an email confirmation will be sent to the email address you provided to registration. If you made an error entering your email address to registration, your purchase confirmation and tracking information may not arrive. Should you have any questions, please contact us at info@bestlife.com or call us at +94 (0)38 492 7322/ 23/ 24 between 9am and 5pm, Monday through Saturday.";
                    //Response.Redirect("Home.aspx");

                    //conf.Text = "Welcome To BestLife";

                    //backbutton.Visible = true;
                }
                //}
            }
            //dupchs.UserPurchase_Add();
            #endregion
        }
        return transact_Ok;

    }
    #endregion
    


    #region Rebind

    public void reBind()
    {
        List<Bestlife.ERP.Entities.Return_to_R> listrtn = new List<Bestlife.ERP.Entities.Return_to_R>();
        List<Bestlife.ERP.Entities.Tocheck_To_cart> listrtntocheck = new List<Bestlife.ERP.Entities.Tocheck_To_cart>();
        listrtn.Clear();
        listrtntocheck.Clear();
        if (Session["cart"] != null)
        {
            shoppingCheck = (Bestlife.ERP.BusinessRules.Shopping_Cart)Session["cart"];
            
            TOTAMOUNT.Visible = false;
            TOTPV.Visible = false;
            TOTBV.Visible = false;
     
            if (shoppingCheck.Items.Count > 0)
            {
              //  TOTAMOUNT.BackColor = System.Drawing.Color.LightBlue;
                TOTAMOUNT.Visible = true;
                TOTPV.Visible = true;
                TOTBV.Visible = true;
                TOT.Visible = true;
                #region to recipt

                listrtn = shoppingCheck.reciptvalues;
                GridView2.DataSource = listrtn;
                GridView2.DataBind();

                TOTAMOUNT.Text = "" + shoppingCheck.total;
                TOT.Text = "" + shoppingCheck.total;
                TOTPV.Text = "" + shoppingCheck.totalPoint_value;
                TOTBV.Text = "" + shoppingCheck.totalBusiness_Value;
                TOTDIS.Text = "" + shoppingCheck.Tot_discounttot;
                TOTRETAIL.Text = "" + shoppingCheck.total_Rprice;
                TOTQTY.Text = "" + shoppingCheck.total_quantity;


                #endregion

            }

        }
    }

    public string rcptno()
    {
        Bestlife.ERP.DataAccess.ReturncountForRecipt rsp = new Bestlife.ERP.DataAccess.ReturncountForRecipt();
        rcpt = rsp.ReturnReciptID();
        invoiceids = "BC" + rcpt.ToString();
        repid.Text = invoiceids;

        return invoiceids;

    }
    #endregion

    protected void ASPxButton2_Click(object sender, EventArgs e)
    {
        HttpContext.Current.Response.Redirect("invoice.aspx?rcptID=" + repid.Text);
    }
    protected void ASPxButton3_Click(object sender, EventArgs e)
    {
        Session["user"] = null;
        Session["name"] = null;
        Session["cartview"] = null;
        Session["cart"] = null;
        Response.Redirect("PointOfSales.aspx");
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        Checkout.Enabled = true;
        GridView1.EditIndex = -1;
        BindGridView();
    }
    protected void TextBox2_TextChanged(object sender, EventArgs e)
    {
        #region Enable button

        PrintButton.Enabled = true;
      //  Checkout.Enabled = true;

        #endregion

        double amounts = 0;
        double total=double.Parse(TOT.Text);
        if (amount.Equals(""))
        {

        }
        else
        {
            amounts = double.Parse(amount.Text);
        }
        Bestlife.ERP.DataAccess.Pricecheckup chkp = new Bestlife.ERP.DataAccess.Pricecheckup();
        double balance = amounts - total;

        BALANSlBL.Text = chkp.returnPrice(balance.ToString());


    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Checkout.Enabled = true;
    }

    public Boolean idisok(string ids)
    {
        Boolean tf = false;

        int idlength = ids.Length;
        string lastch = ids.Substring(idlength - 1);

        if ((lastch.Equals("V") || lastch.Equals("v") || lastch.Equals("X") || lastch.Equals("x")) && (ids.Length<10))
        {
            tf = true;
        }

        return tf;
    }
}